package com.liujit.standard.basis.generator.service;

import cn.hutool.core.util.StrUtil;
import com.liujit.standard.basis.generator.action.model.DbColumnType;
import com.liujit.standard.basis.generator.action.model.Table;
import com.liujit.standard.basis.generator.action.model.TableInfo;
import com.liujit.standard.basis.generator.action.model.Template;
import com.liujit.standard.basis.generator.config.DataSourceConfig;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 表工具类
 * @Author LiuJun
 * @Date 2020/8/14 9:51 上午
 */
@Slf4j
public class GeneratorService {

    private DataSourceConfig dataSourceConfig;

    public GeneratorService setDataSourceConfig(DataSourceConfig dataSourceConfig) {
        this.dataSourceConfig = dataSourceConfig;
        return this;
    }

    public GeneratorService setDataSourceConfig(String driverName, String username, String password, String url) {
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDriverName(driverName);
        dataSourceConfig.setUsername(username);
        dataSourceConfig.setPassword(password);
        dataSourceConfig.setUrl(url);
        this.dataSourceConfig = dataSourceConfig;
        return this;
    }

    /**
     * 查询数据库表信息
     *
     * @param schema
     * @return
     */
    public List<Table> getTable(String schema) {
        {
            // 获取数据库连接，查询表结构信息
            Connection conn = dataSourceConfig.getConn();
            Statement sm = null;
            List<Table> tables = new ArrayList<>();
            try {
                sm = conn.createStatement();
                String sql = "select table_name,table_comment from information_schema.`tables` where table_schema = '"
                        + schema + "' order by table_name desc";
                System.out.println(sql);
                ResultSet rs = sm.executeQuery(sql);
                while (rs.next()) {
                    Table table = new Table();
                    table.setName(rs.getString(1));
                    table.setComment(rs.getString(2));
                    table.setLabel(table.getName() + "-" + table.getComment());
                    tables.add(table);
                }
            } catch (SQLException e) {
               log.error(e.getMessage());
            }
            if (sm != null) {
                try {
                    sm.close();
                } catch (SQLException e) {
                   log.error(e.getMessage());
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    log.error(e.getMessage());
                }
            }
            return tables;
        }
    }

    /**
     * 查询表结构信息
     *
     * @param tableName
     * @return
     */
    public List<TableInfo> getTableInfo(String tableName) {
        Connection conn = dataSourceConfig.getConn();
        Statement sm = null;
        List<TableInfo> tableInfos = new ArrayList<>();
        try {
            sm = conn.createStatement();
            String sql = "select column_name, data_type, column_comment from information_schema.columns where table_schema = (select database()) and table_name = '"
                    + tableName + "'";
            System.out.println(sql);
            ResultSet rs = sm.executeQuery(sql);
            while (rs.next()) {
                TableInfo tableInfo = new TableInfo();
                tableInfo.setName(rs.getString(1));
                DbColumnType column = DbColumnType.get(rs.getString(2));
                tableInfo.setType(column.getType());
                tableInfo.setJdbcType(column.getJdbcType());
                tableInfo.setComment(rs.getString(3));
                tableInfo.setPropertyName(StrUtil.toCamelCase(tableInfo.getName()));
                tableInfos.add(tableInfo);
            }
            if (tableInfos.size() > 0) {
                TableInfo t = tableInfos.get(tableInfos.size() - 1);
                tableInfos.remove(tableInfos.size() - 1);
                t.setLast(true);
                tableInfos.add(t);
            }
        } catch (SQLException e) {
           log.error(e.getMessage());
        }
        if (sm != null) {
            try {
                sm.close();
            } catch (SQLException e) {
                log.error(e.getMessage());
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                log.error(e.getMessage());
            }
        }
        return tableInfos;
    }

    /**
     * 获取模板内容
     *
     * @return
     */
    public List<Template> getTemplate() {
        List<Template> templates = new ArrayList<>();
        templates.add(create("controllerSwitch", "controller-模板"));
        templates.add(create("serviceSwitch", "service-模板"));
        templates.add(create("mapperSwitch", "mapper-模板"));
        templates.add(create("xmlSwitch", "mapper-xml-模板"));
        templates.add(create("modelSwitch", "model-模板"));
        templates.add(create("querySwitch", "query-模板（列表查询参数，默认全部model内容）"));
        return templates;
    }

    private static Template create(String name, String comment) {
        Template template = new Template();
        template.setName(name);
        template.setComment(comment);
        return template;
    }
}
